package com.wedu.modules.dss;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import java.util.UUID;

/**
 * oss
 */
@Component
public class AliyunOSSUtils {


    //域名
    private String endpoint = "https://oss-cn-nanjing.aliyuncs.com";
    // STS临时访问密钥AccessKey ID和AccessKey Secret。
    private String accessKeyId = "LTAI5tLP1JPD5zMJi7nfs9Nm";
    private String accessKeySecret = "1DgIzzq0eFq0hqEIdbbHRfPcdrwics";
    //bucket存储空间名
    private String bucketName = "device-management666";

    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile file) throws IOException, ClientException {


        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖--通过UUID修改图片的唯一标识码 -- 名称SDW
        String originalFilename = file.getOriginalFilename();
        //生成一段不重复的字符
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));   // 截取文件名的后缀

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        //文件访问路径
        // https://存储空间名.域名/文件名
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }

}